package com.fingard.dsp.bank.directbank.cmb05;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.FGBiz;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.google.gson.Gson;
import net.sf.json.JSONArray;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName CMB05Balance
 * @Author Zhengzy
 * @Date 2020/3/26 10:24
 * @Version 1.0
 **/
public class CMB05Balance extends CMB05Base implements IBalance {
    // 明细查询会用到账号-户口号，户口号在余额查询的返回中，故在余额查询是对数据入库  urid bankcode  账号 户口号
    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,REQSEQID,BANKREQSEQID) values (?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;"; // 账号=？，bankcode=？


    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        // 余额返回给ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();
        Connection conn = FGBiz.getLocalDbConn();
        WriteBankLogLn("进入余额查询处理类");
        StringBuffer sbf = new StringBuffer();
        CMB05Header bankHeader = new CMB05Header();
        bankHeader.transCode = "DCDACCYE";
        // 组装请求前缀
        writeCommonHeader(sbf, bankHeader);
        // 组装请求报文体json
        JSONObject json = new JSONObject();
        HashMap<String, Object> requestMap = new HashMap<String, Object>();
        HashMap<String, String> headMap = new HashMap<String, String>();
        headMap.put("funcode", bankHeader.transCode);
        headMap.put("userid", bankFront.loginName);
        requestMap.put("head", headMap);
        HashMap<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("ctnkey", "");// 第一次传空 如返回报文有该字段 则将值赋到请求报文中
        requestMap.put("body", bodyMap);
        json.put("request", requestMap);
        sbf.append(JSON.toJSONString(json));
        int firstReq = 1; // 用来判断是否续传

        while (firstReq == 1) { // 还有数据，继续请求
            // 发送到银行
            String[] tmpStrRet = sendToBank(sbf.toString(), p_req7506.reqHeader.transType, p_req7506.reqHeader.transType);
            if (tmpStrRet[0].length() == 0) {
                // 把结果转成json
                JSONObject response = JSON.parseObject(tmpStrRet[1]);
                if (response != null) {
                    String info = response.getString("response");
                    JSONObject content = JSON.parseObject(info);
                    String head = content.getString("head");
                    String body = content.getString("body");
                    Gson gson = new Gson();
                    Map<String, String> headInfo = new HashMap<String, String>();
                    Map<String, String> bodyInfo = new HashMap<String, String>();
                    headInfo = gson.fromJson(head, headInfo.getClass());
                    if (headInfo != null) {
                        String responseCode = headInfo.get("resultcode");
                        String responseMsg = headInfo.get("resultmsg");
                        if ("SUC0000".equals(responseCode)) {
                            JSONObject bodyInfos = JSON.parseObject(body);
                            String args = bodyInfos.getString("actlis");
                            String ctnkey = bodyInfos.getString("ctnkey");// 查看银行返回是否有ctnkey，有则续传
                            WriteBankLogLn("续传标志中的内容：" + ctnkey + "。");
                            if ("null".equals(ctnkey) || StringHelper.isNullOrEmpty(ctnkey)) { // 是否需要续传 有该字段
                                firstReq = 0;
                                WriteBankLogLn("不需要续传，ctnkey：" + ctnkey);
                            } else { // 需要续传
                                // 修改原报文，用于再次请求
                                sbf = new StringBuffer();
                                writeCommonHeader(sbf, bankHeader);
                                bodyMap.remove("ctnkey");
                                bodyMap.put("ctnkey", ctnkey);
                                requestMap.remove("body");
                                requestMap.put("body", bodyMap);
                                json.put("request", requestMap);
                                sbf.append(JSON.toJSONString(json));
                            }
                            // 不管需要不需要续传 都把本次返回的数据处理了
                            JSONArray array = JSONArray.fromObject(args);
                            String act = "";// 要查询的账号
                            // 返回的多个账号中有要查询的账号
                            double currBal = 0.0;//当前余额
                            while (p_req7506.readRecord()) {
                                act = p_req7506.readedDetail.actNum;
                                WriteBankLogLn("要查询的账号：" + act);

                                for (int i = 0; i < array.size(); i++) {
                                    RetAtsBalDetail detail = new RetAtsBalDetail();
                                    String record = array.getString(i);
                                    Map<String, String> recordInfo = new HashMap<String, String>();
                                    recordInfo = gson.fromJson(record, recordInfo.getClass());
                                    String act1 = recordInfo.get("eacnbr");// 每条记录中的账号
                                    if (act.equals(act1)) {
                                        detail.respCode = "0";
                                        detail.availBal = recordInfo.get("avlbal");// 可用余额
                                        detail.frozenBal = recordInfo.get("hldbal");// 冻结余额
                                        currBal = Double.parseDouble(detail.availBal) + Double.parseDouble(detail.frozenBal);//当前余额
                                        detail.currBal = String.valueOf(currBal);// 当前余额
                                        detail.actNum = act;// 账号
                                        detail.actCur = convertCurToATS(recordInfo.get("ccynbr"));// 币种
                                        retAts.writeRetDetail(detail, p_req7506.isBatch);
                                        String eacnbr = recordInfo.get("eacnbr");// 就是用户账号
                                        String actnbr = recordInfo.get("actnbr");// 存储用于明细查询

                                        // 户口号是否被存了
                                        Map<String, Object> map = JDBCHelper.execQuerySingle(conn, SELECTRECEIPT, new Object[]{eacnbr, p_req7506.reqHeader.bankCode});
                                        if (map.size() == 0) {
                                            // 没有存该账号和对应的户口号，入库
                                            WriteBankLogLn("客户号：" + eacnbr + " 没有入库，进行入库操作。");
                                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                            JDBCHelper.update(conn, INSERTRECEIPT, new Object[]{uuid, p_req7506.reqHeader.bankCode, eacnbr, actnbr});
                                        }
                                    } else {
                                        // 不是要查询的账号
                                        continue;
                                    }

                                }
                            }
                        } else {
                            firstReq = 0; // 返回异常，不续传，无法续传
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(responseMsg);
                        }
                    }
                } else {
                    firstReq = 0;
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("请求未正常返回");
                }
            } else {
                firstReq = 0;
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        }
        conn.close();
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        if (getBankConfig().getValueAsBool("useFMA2PCHK")) {
            return FMA2PCHK(p_req7505);
        }
        return null;
    }

    public RetAts7505HisBalQry FMA2PCHK(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        retAts.writeStart();
        try {
            //ATSES-27134 正大天晴CMB05公转私超过5w用途限定值
            //支付前需要调用FMA2PCHK接口，但实际生产又不上这个接口，故写在这里支付前，人工查历史余额调用一下打印结果在日志上
            StringBuffer sbf = new StringBuffer();
            CMB05Header bankHeader = new CMB05Header();
            bankHeader.transCode = "FMA2PCHK";
            bankHeader.reqSeqID = getQryTransID();
            //组装请求前缀
            writeCommonHeader(sbf, bankHeader);
            //组装请求报文体json
            JSONObject json = new JSONObject();
            HashMap<String, Object> requestMap = new HashMap<String, Object>();
            HashMap<String, String> headMap = new HashMap<String, String>();
            HashMap<String, String> bodyMap = new HashMap<String, String>();
            headMap.put("funcode", bankHeader.transCode);
            headMap.put("userid", bankFront.loginName);
            //	head.put("head",headMap);
            requestMap.put("head", headMap);
            bodyMap.put("rcveac", p_req7505.actNum);//收方账户
            bodyMap.put("rcvean", "");//收方户名
            bodyMap.put("ccynbr", "10");//10：人民币
            bodyMap.put("trsamt", "60000");//查询5W以上用途
            requestMap.put("body", bodyMap);
            json.put("request", requestMap);
            sbf.append(JSON.toJSONString(json));
            String[] tmpStrRet = sendToBank(sbf.toString());

            if (tmpStrRet[0].length() == 0) {
                //把结果转换成json
                JSONObject response = JSON.parseObject(tmpStrRet[1]);
                if (response != null) {
                    String info = response.getString("response");
                    JSONObject content = JSON.parseObject(info);
                    String head = content.getString("head");
                    Gson gson = new Gson();
                    Map<String, String> headInfo = new HashMap<String, String>();
                    headInfo = gson.fromJson(head, headInfo.getClass());
                    if (headInfo != null) {
                        String responseCode = headInfo.get("resultcode");
                        if (responseCode != null && responseCode.equals("SUC0000")) {
                            retAts.writeRespCode("0");
                        } else {
                            //通讯无异常 不存在超时响应问题 指令提交失败
                            retAts.writeRespCode("-1");
                        }
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("请求未正常返回");

                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
        }
        RetAtsHisBalDetail detail = new RetAtsHisBalDetail();
        retAts.writeRetDetail(detail);
        return retAts;
    }
}
